package com.ty.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ty.annotation.Auth;
import com.ty.entity.Book;
import com.ty.entity.BookTypeEntity;
import com.ty.resp.CommonResp;
import com.ty.service.IBookTypeService;
import com.ty.service.IBookService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : txy
 * @create : 2024/1/9 16:15
 */
@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    private IBookService IBookService;
    @Resource
    private IBookTypeService bookTypeService;
    @Resource
    private JavaMailSender mailSender;

    @Value("${coverPath}")
    private String coverPath;

    //查询
    @GetMapping("/getBooks")
    public CommonResp getBooks(@RequestParam(value = "page", defaultValue = "1") Integer page,
                               @RequestParam(value = "size", defaultValue = "10") Integer size,
                               @RequestParam(value = "orderBy", required = false) String orderBy,
                               @RequestParam(value = "search", required = false) String search) {
        return IBookService.queryAll(new Page<>(page, size), orderBy, search);
    }

    //分类查询
    @GetMapping("/getBooksByTypeAndName")
    public CommonResp getBooksByType(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "size", defaultValue = "10") Integer size,
            @RequestParam("type") Integer type,
            @RequestParam("name") String name) {
        CommonResp resp = new CommonResp();
        Page<Book> pes;
        //先查询类型
        if ("".equals(type) || type == null || type == 0) {
            pes = IBookService.queryByName(new Page<>(page, size), name);
            for (Book pe : pes.getRecords()) {
                BookTypeEntity pt = bookTypeService.selectByTypeId(pe.getType());
                pe.setPt(pt);
            }
        } else {
            BookTypeEntity typeEntity = bookTypeService.selectByTypeId(type);
            pes = IBookService.queryByType(new Page<>(page, size), name, type);
            for (Book pe : pes.getRecords()) {
                pe.setPt(typeEntity);
            }
        }
        resp.setContent(pes);
        return resp;
    }

    //排行榜
    @GetMapping("/getBooksGroupByType")
    public CommonResp getBooksById() {
        CommonResp resp = new CommonResp();
        Map<String, Page<Book>> result = new HashMap<>();
        List<BookTypeEntity> typeEntities = bookTypeService.selectAll();
        typeEntities.forEach((x) -> {
            Page<Book> page = IBookService.queryByType(new Page<>(1, 10), "", x.getId());
            result.put(x.getName(), page);
        });
        resp.setContent(result);
        return resp;
    }

    //根据id查，图书详情
    @GetMapping("/getBookById")
    public CommonResp getBookById(Integer id) {
        CommonResp resp = new CommonResp();
        Book periodical = IBookService.queryById(id);
        BookTypeEntity typeEntity = bookTypeService.selectByTypeId(periodical.getType());
        periodical.setPt(typeEntity);
        resp.setContent(periodical);
        return resp;
    }

    //修改期刊
    @Auth(roles = "admin")
    @PostMapping("/updateBook")
    public CommonResp updateBook(Book periodical) {
        boolean update = IBookService.updateById(periodical);
        CommonResp resp = new CommonResp();
        if (!update) {
            resp.setMessage("数据有问题，新增失败");
        }
        resp.setSuccess(update);
        return resp;
    }

    //新增期刊
    @Auth(roles = "admin")
    @PostMapping("/addBook")
    public CommonResp addBook(Book periodical) {
        boolean save = IBookService.save(periodical);
        CommonResp resp = new CommonResp();
        if (!save) {
            resp.setMessage("数据有问题，新增失败");
        }
        resp.setSuccess(save);
        return resp;
    }

    //删除期刊
    @Auth(roles = "admin")
    @DeleteMapping("/deleteBook")
    public CommonResp deleteBook(@RequestParam(value = "id") Integer id,
                                 @RequestParam(value = "coverAddress") String coverAddress) {
        CommonResp resp = new CommonResp();
        boolean remove = IBookService.removeById(id);
        if (remove) {
            deleteFile(coverAddress);
        }
        resp.setSuccess(remove);
        return resp;
    }

    @Auth(roles = "admin")
    @DeleteMapping("/deleteBooks")
    public CommonResp deleteBooks(Integer[] id) {
        CommonResp resp = new CommonResp();
        boolean remove = IBookService.removeById(id);
        resp.setSuccess(remove);
        return resp;
    }

    //上传封面
    @Auth(roles = "admin")
    @PostMapping("/uploadFile")
    public CommonResp uploadFile(MultipartFile file) {

        String filename = file.getOriginalFilename();
        //扩展名
        String ext = filename.substring(filename.lastIndexOf("."));
        String newFileName = UUID.randomUUID() + ext;
        try {
            file.transferTo(new File(coverPath + newFileName));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        CommonResp result = new CommonResp();
        result.setMessage(newFileName);
        return result;
    }
    //查询库存不足20本的
    @Auth(roles = "admin")
    @GetMapping("/getBooksByNum")

    public CommonResp getBooksByNum(Integer num){
        CommonResp resp = new CommonResp();
        resp.setContent(IBookService.getBooksByNum(num));
        return resp;
    }
    //每小时执行一次
    @Scheduled(cron = "0 0 * * * *")
    public void inventoryAlert() throws MessagingException {
        /*//只能发送文本邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //setBcc秘密发送，只有对方可以看,setCc抄送给谁，这个人可以看但不需要做事，比如老板, setTo发送给谁
        message.setTo("2336162028@qq.com");//接收人
        message.setFrom("2194145064@qq.com");//发送人
        message.setSubject("邮件测试");
        message.setText("这是一封邮件测试<a href='https://www.baidu.com'/>");*/
        List<HashMap<String, String>> booksByNum = IBookService.getBooksByNum(20);
        if (!booksByNum.isEmpty()){
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);
            messageHelper.setTo("2194145064@qq.com");//接收人
            messageHelper.setFrom("2194145064@qq.com");//发送人
            messageHelper.setSubject("期刊订阅系统库存预警");
            messageHelper.setText("有期刊库存不足啦，登录管理系统查看吧。<a href='https://www.baidu.com'>去查看</a>",true);
            mailSender.send(message);
        }
    }
    //删除封面
    public void deleteFile(String fileName) {
        File file = new File(coverPath + fileName);
        //判断文件是否存在
        if (file.exists() == true) {
            Boolean flag;
            flag = file.delete();
            if (flag) {
                System.out.println("成功删除图片" + file.getName());
            } else {
                System.out.println("删除失败");
            }
        } else {
            System.out.println("图片不存在，终止操作");
        }
    }

}
